// 格式化时间（xxxx年xx月xx日 xx:xx）
function getformatTime(time: Date) {
	const year = time.getFullYear()
	const month = time.getMonth() + 1
	const day = time.getDate()
	const hour = time.getHours()
	const min = time.getMinutes()
	return `${year}-${month}-${day} ${hour}:${min}`
}

export default {
	checkPhone(phone: string) {
		const reg = /^1[3|4|5|6|7|8][0-9]{9}$/
		if (reg.test(phone)) {
			return true
		}
		return false
	},
	// 格式化时间（根据传入时间，与当前时间相比得出几天前，几小时前，几分钟或者是刚刚）
	//时间函数date格式为：xxxx-xx-xx xx:xx
	formatMessageDate(date: string) {
		var newTime = Date.parse(new Date() as any) //获得当前时间，转化时间戳
		var interval = (newTime - new Date(date).getTime()) / 1000

		if (interval < 0) {
			return '刚刚'
		} else if (interval > 24 * 3600) {
			return getformatTime(new Date(date))
		} else if (interval > 3600) {
			return Math.round(interval / 3600) + '小时前'
		} else if (interval > 60) {
			return Math.round(interval / 60) + '分钟前'
		} else {
			return '刚刚'
		}
	},
	formatTime(date: Date) {
		const year = date.getFullYear()
		const month = date.getMonth() + 1
		const day = date.getDate()
		const hour = date.getHours()
		const min = date.getMinutes()
		return `${year}-${month}-${day} ${hour}:${min < 10 ? '0' + min : min}`
	},
	getFileSuffixName(fileName: string) {
		const index = fileName.lastIndexOf('.')
		return fileName.substring(index + 1)
	},
	// 获取base64
	async readerFile(file: File) {
		return new Promise((resolve, reject) => {
			const reader = new FileReader()
			let fileUrl = ''
			reader.readAsDataURL(file)
			reader.onload = (e) => {
				fileUrl = e.target?.result as string
				resolve(fileUrl)
			}
			reader.onerror = (err) => {
				reject(err)
			}
		})
	},
	// 获取图片宽高比例
	imgScale(file: File) {
		return new Promise((resolve) => {
			const img = new Image()
			img.src = URL.createObjectURL(file)
			img.onload = () => {
				resolve(img.width / img.height)
				// 始方URL对象引用
				URL.revokeObjectURL(img.src)
			}
		})
	},
	// 获取视频封面
	async getVideoCover(file) {
		return new Promise((resolve) => {
			const reader = new FileReader()
			reader.readAsDataURL(file)
			reader.onload = function (e: any) {
				let video = document.createElement('video')
				video.setAttribute('src', e.target.result)
				video.setAttribute('controls', 'controls')
				video.setAttribute('width', '260')
				video.setAttribute('height', '160')
				video.currentTime = 1 // 视频时长，一定要设置，不然大概率白屏
				video.addEventListener('loadeddata', function () {
					let canvas = document.createElement('canvas')
					let width = video.width
					let height = video.height
					canvas.width = width
					canvas.height = height
					canvas.getContext('2d')?.drawImage(video, 0, 0, width, height) // 绘制canvas
					let dataURL = canvas.toDataURL('image/png') // 转换为base64
					resolve(dataURL)
				})
			}
		})
	},
	formatFileSize(bytes: number) {
		const units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']
		let size = bytes
		let unitIndex = 0

		while (size >= 1024 && unitIndex < units.length - 1) {
			size /= 1024
			unitIndex++
		}

		// 保留两位小数，四舍五入
		size = Math.round(size * 100) / 100

		return `${size}${units[unitIndex]}`
	},
	// 防抖
	debounce(fn: Function, delay: number = 500) {
		let timer = null
		const _debounce = function (...args) {
			if (timer) clearTimeout(timer)
			timer = setTimeout(() => {
				fn.call(this, ...args)
			}, delay)
		}
		return _debounce
	},
	// 节流
	throttle(fn, interval) {
		let lastTime = 0
		const _throttle = function (...args) {
			let nowTime = new Date().getTime()
			let reTime = interval - (nowTime - lastTime)
			if (reTime <= 0) {
				fn.call(this, ...args)
				lastTime = nowTime
			}
		}
		return _throttle
	}
}
